package com.qf.realm;

import com.alibaba.druid.util.StringUtils;
import com.qf.entity.User;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.realm
 * @Description:
 * @Date 2022/10/10 17:31
 */
@SuppressWarnings("all")
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //主要的，在认证方法中返回的user
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //在数据库中根据用户id查询对应角色信息
        Set<String> roles = roleService.selectByUid(user.getId());
        //角色  的set集合
        authorizationInfo.setRoles(roles);
        //在数据库中查询对应的权限信息
        Set<String> perms = menuService.findPermisByUid(user.getId());
        //权限的set集合
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取token传入的用户名和密码，注意密码是明文，和数据库交互需要MD5加密
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw  new RuntimeException("用户名或密码为空");
        }

//        因为用户名不能有一样的，所以只需要查找用户名即可
        User user = userService.selectByName(username);

        if(user == null ){
            throw new UnknownAccountException("用户不存在");
        }

        //判断用户的状态是否可以使用
        if(user.getStatus() == 0 ){
            throw new LockedAccountException("账户已锁定");
        }

        //判断密码
        String passwordUser = user.getPassword();
        System.out.println(passwordUser);
        if(!password.equalsIgnoreCase(passwordUser)){
            throw new CredentialsException("密码错误");
        }
            //感觉很想session
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),user.getRealname());

        return info;
    }
}
